// web hosting的配置
// 包括所有web请求的路由
// 所有请求的实际函数放在web目录中

var domain = require('domain');
var path = require('path');
var express = require('express');
var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session');
var connect = require('connect');
var bodyParser = require('body-parser');
var cloud = require('./cloud');
var AV = require('leanengine')
var multiparty = require('multiparty');


var app = express();

// App 全局配置
app.set('views', path.join(__dirname, "views")); // 设置模板目录
app.set('view engine', 'ejs'); // 设置 template 引擎
app.use(cloud);
app.use(express.static('public')); // 设置静态文件目录
// parse application/json
app.use(bodyParser.json());
app.use(cookieParser());

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
	extended: true
}));
// 启用 cookieParser
//app.use(express.cookieParser('Your Cookie Secure'));
app.use(AV.Cloud.CookieSession({
	secret: 'my secret',
	maxAge: 3600000,
	fetchUser: true
}));

// 使用 cookieSession 记录自定义信息到 cookie
app.use(cookieSession({
	name: 'session',
	keys: ['key1', 'key2']
}))

//解析支付宝头部
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  type: function(req) {
    return /x-www-form-urlencoded/.test(req.headers['content-type']);
  },
  extended: false,
  proxy: true,
  resave: true,
  saveUninitialized: true
}));

// http请求函数引用
var official_index = require('./cloud/web/offical/index');
var admin_index = require('./cloud/web/admin/index');
var admin_recommendUser = require('./cloud/web/admin/recommendUser');
//var admin_gift = require('./cloud/web/admin/gift');
var alipay = require('./cloud/web/ali/alipay');
var wxpay = require('./cloud/web/ali/wxpay');
var memberPay = require('./cloud/web/ali/memberPay');
var mpServerManager = require('./cloud/web/admin/serverManager');

var admin_home_article = require('./cloud/web/admin/homeArticle');
var admin_member_manage= require('./cloud/web/admin/memberManager');
var admin_report=require('./cloud/web/admin/report');
var admin_feedback=require('./cloud/web/admin/feedback');
var admin_mistake = require('./cloud/web/admin/mistake');
var admin_wx_article = require('./cloud/web/admin/wxArticle');


/***************** Express 路由 API 服务 *****************/

/*************** 官方网站****************/
// 网站首页
app.get('/index', official_index.getIndex);
app.get('/about', official_index.getAboutIndex);
app.get('/server', official_index.getServerIndex);
app.get('/notice', official_index.getNoticeIndex);
app.get('/handle',official_index.getHandleIndex);



//// wap下载页面
//app.get('/wap', index.getWapIndex);
// 协议
app.get('/protocol', official_index.getProtocol);

//wap 会员缴费
app.get("/member/pay",memberPay.getMemberPayIndex);
app.post("/member/pay/wxnotify",memberPay.wxnotify);
app.post("/member/pay/alinotify",memberPay.alinotify);
//wap充值
app.get("/wap/pay", alipay.getPayIndex);
app.post("/wap/pay", alipay.pay);
app.post("/wap/pay/notify", alipay.notify);

app.post("/wxpay",wxpay.pay);
app.get("/wxpay/payIndex",wxpay.payIndex);
app.post("/wxpay/notify",wxpay.notify);
//app.get("/wxpay/notify",wxpay.notify);

/*************** admin管理平台 ****************/

app.get('/admin', admin_index.getIndex);

app.post('/admin/login', admin_index.postLogin);

//调用此url来登出帐号
app.get('/admin/logout', admin_index.getLogout);

//查看用户信息
app.get('/admin/userinfo', admin_index.getUserInfo);

/*****************微信宣传文章管理********************/
app.get('/wx/article',admin_wx_article.getWxArticle);
app.get('/wx/article/wap',admin_wx_article.getWxWap);
app.get('/admin/weixin/article/write',admin_wx_article.writeAritcleIndex);
app.post('/admin/weixin/article/add',admin_wx_article.addArticle);
app.get('/admin/weixin/article/all',admin_wx_article.getArticle);
app.get('/admin/weixin/article/edit',admin_wx_article.editArticleIndex);
app.post('/admin/weixin/article/edit',admin_wx_article.editArticle);

/*****************主页文章管理********************/
app.get('/admin/home/article/write',admin_home_article.writeAritcleIndex);
app.get('/home/article',admin_home_article.getSimpleArticle);
app.post('/admin/home/article/upload',admin_home_article.uploadArticleImg);
app.post('/admin/home/article/add',admin_home_article.addArticle);
app.get('/admin/home/article/all',admin_home_article.getArticle);
app.get('/admin/home/article/edit',admin_home_article.editArticleIndex);
app.post('/admin/home/article/edit',admin_home_article.editArticle);

/*****************会员管理********************/
app.get('/admin/member/apply',admin_member_manage.getMemberApplyIndex);
app.post('/admin/member/apply/handle',admin_member_manage.handleApply);
app.post('/admin/member/contact',admin_member_manage.contact);
app.get('/admin/member',admin_member_manage.getSingleMember);

app.get('/member/article',admin_member_manage.getMemberArticleIndex);
app.get('/admin/member/article/add',admin_member_manage.getArticleAddIndex);
app.post('/admin/member/article/add',admin_member_manage.addMemberArticle);
app.get('/admin/member/article/edit',admin_member_manage.getEditIndex);
app.post('/admin/member/article/edit',admin_member_manage.editMemberArticle);
app.post('/admin/member/article/publish',admin_member_manage.publishMemberArticle);

// 用户举报处理
app.get('/admin/report', admin_report.getReport);

app.post('/admin/report', admin_report.handleReport);

app.post('/admin/reportContact', admin_report.reportContact);

app.post('/admin/report/neverScreen', admin_report.neverScreen);

app.post('/admin/report/cancleScreen', admin_report.cancleScreen);

// 处理用户反馈
app.get('/admin/feedback', admin_feedback.getFeedback);
app.get('/admin/feedback/handler', admin_feedback.getFeedbackHandler);
app.post('/admin/feedback/handler', admin_feedback.handleFeedback);

/*************** 违规操作管理 ***************/
app.get("/admin/mistake/view",admin_mistake.getWaitingView);
//忽略
app.post("/admin/mistake/pass",admin_mistake.passview);
//警告并回复
app.post("/admin/mistake/alert",admin_mistake.alertReply);
app.post("/admin/mistake/alertId",admin_mistake.alertReplyById);
//封号
app.post("/admin/mistake/close",admin_mistake.disableUser);
app.post("/admin/mistake/closeWithId",admin_mistake.disableUserWithId);
//恢复身份
app.post("/admin/mistake/resume",admin_mistake.resumeUser);
app.post("/admin/mistake/resumeWithId",admin_mistake.resumeUserWithId);

app.get("/admin/mistake/review",admin_mistake.getReView);
app.get("/admin/mistake/member",admin_mistake.getMisMember);

/*************** 礼物管理 ***************/
//app.get("/admin/gift", admin_gift.getGift);
//// 编辑
//app.get('/admin/gift/edit', admin_gift.getGiftEdit);
//app.post('/admin/gift/edit', admin_gift.giftEdit);
//// 新增
//app.get('/admin/gift/add', admin_gift.getGiftAdd);
//app.post('/admin/gift/add', admin_gift.giftAdd);
//// 上架
//app.post('/admin/gift/publish', admin_gift.publishGift);
//// 下架
//app.post('/admin/gift/disable', admin_gift.disableGift);

/*************** 推荐用户管理 ***************/
app.get('/admin/pocketUser', admin_recommendUser.getPocketUser);
//app.get('/admin/recommendUser', admin_recommendUser.getUser);
//// 身份转化
//app.post('/admin/recommendUser/setEdit', admin_recommendUser.setEdit);
//app.post('/admin/recommendUser/setPocket', admin_recommendUser.setPocket);
//// 编辑
//app.get('/admin/recommendUser/edit', admin_recommendUser.getUserEdit);
//app.post('/admin/recommendUser/edit', admin_recommendUser.userEdit);
//// 新增
//app.get('/admin/recommendUser/add', admin_recommendUser.getUserAdd);
//app.post('/admin/recommendUser/add', admin_recommendUser.userAdd);
////删除
//app.post('/admin/recommendUser/delete', admin_recommendUser.deleteRecmmandUser);
////查找用户
//app.post('/admin/recommendUser/find', admin_recommendUser.findRecmmandUser);
////真人认证用户 type=0 普通 type=1 真人
//app.post('/admin/recommendUser/realAuthentic', admin_recommendUser.realAuthentic);

/******************美陪服务内容管理 ***********/
app.get('/admin/server', mpServerManager.getServer);
// 编辑
app.get('/admin/server/edit', mpServerManager.getServerEdit);
app.post('/admin/server/edit', mpServerManager.serverEdit);
// 新增
app.get('/admin/server/add', mpServerManager.getServerAdd);
app.post('/admin/server/add', mpServerManager.serverAdd);
// 上架
app.post('/admin/server/publish', mpServerManager.publishServer);
// 下架
app.post('/admin/server/disable', mpServerManager.disableServer);
// 删除
app.post('/admin/server/delete', mpServerManager.deleteServer);


//app 本地处理函数
app.locals.Format = function(date) {
	var fmt = "yyyy-MM-dd hh:mm:ss";
	var o = {
		"M+": date.getMonth() + 1, //月份 
		"d+": date.getDate(), //日 
		"h+": date.getHours(), //小时 
		"m+": date.getMinutes(), //分 
		"s+": date.getSeconds(), //秒 
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度 
		"S": date.getMilliseconds() //毫秒 
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

// 未处理异常捕获 middleware
// 未处理异常捕获 middleware
app.use(function(req, res, next) {
	var d = null;
	if (process.domain) {
		d = process.domain;
	} else {
		d = domain.create();
	}
	console.log(req.url)
	d.add(req);
	d.add(res);
	d.on('error', function(err) {
		console.log(req.url);
		console.error('uncaughtException url=%s, msg=%s', req.url, err.stack || err.message || err);
		if (!res.finished) {
			res.statusCode = 500;
			res.setHeader('content-type', 'application/json; charset=UTF-8');
			res.end('uncaughtException');
		}
	});
	d.run(next);
});


// 如果任何路由都没匹配到，则认为 404
// 生成一个异常让后面的 err handler 捕获
app.use(function(req, res, next) {
	var err = new Error('Not Found');
	err.status = 404;
	next(err);
});

// error handlers
app.use(function(err, req, res, next) {
	console.log(err.stack || err.message || err);
	res.status(err.status || 500);
	res.send('error:' + err.message);
});

module.exports = app;
app.listen();